import { BrowserWindow, ipcMain, session } from 'electron'
import { join } from 'path'
import { Conf as Store } from 'electron-conf/main'
import cheerio from 'cheerio'
import { AESCryptoToMd5 } from './utils/aes/index'
import _unescape from './utils/uriparse/unescape'
import dayjs from 'dayjs'
import icon from '../../resources/icon.png?asset'

const electronStore = new Store()

/** 全局 cookie 信息  */
let route_srv_id: string = (electronStore.get('tongtoolCookies') as any[] || []).filter((item) => item.name === 'route_srv_id')?.[0]?.value || '831eebeee2ed995174c5866729e9b548'
let JSESSIONID: string = (electronStore.get('tongtoolCookies') as any[] || []).filter((item) => item.name === 'JSESSIONID')?.[0]?.value || 'A4E410FADC004CA0AAADECD0C2EEAA5E'

type LogInfoType = {
  type: string,
  log: string
}

type PayInfoType = { totalInfo: string, historyInfo: { leftText: string, rightText: string }[] }

/** 全局 记录日志 */
const logger = (event: Electron.IpcMainEvent, logInfo: LogInfoType) => {
  let historyLog = electronStore.get('log') as LogInfoType[] || []
  electronStore.set('log', historyLog.concat([logInfo]))
  console.log(logInfo)
  event.reply('log', logInfo)
}

/** 全局 物流对应的api信息 */
const trackApi = [
  {
    key: 'special.ems.com.cn',
    regExp: /(?<=LZ)(.*)(?=CN)/,
  },
  {
    key: 'api-kmgj-new.rtb56.com',
    regExp: /^KOMON/,
  },
  {
    key: 'www.sdh-scm.com',
    regExp: /^SDH/,
  },
]

/** 替换请求头 */
const replaceLoadHeader = () => {
  const filter = {
    urls: ['*://*.tongtool.com/*'] // 支持通配符
  }
  const headers = {
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0',
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Accept-Language': 'en-US',
  }
  session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    console.log(details.requestHeaders)
    // 必须返回修改后的 headers 和回调
    callback({ requestHeaders: structuredClone(headers) })
  })
}

/** 获取通途-订单信息 */
const getTongToolOrderInfo = (event: Electron.IpcMainEvent, email: string): Promise<any[]> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-订单信息开始: 邮箱 ${email}\n` })

  return new Promise(async (resolve, reject) => {
    const orderQueryResponse = await fetch("https://shiming.tongtool.com/query/order/quickSearchAll", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
        "Referer": "https://shiming.tongtool.com/search/order.htm?search_text_value=ebay%40systemsny.com&search_mark=all&source=global",
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `q_c_all=${encodeURIComponent(email)}&q_c_allString=${encodeURIComponent(email)}&q_c_source=global&q_c_viewOthersHandOrder=true&view=order.quickOrderList&pageSize=100&showCondition=false&condition_prefix=q_c_&`,
      "method": "POST"
    })
    // 订单响应文本
    const orderQueryResponseText = await orderQueryResponse.text()
    // 订单匹配正则
    const orderQueryTextReg = (() => /(?<=querycond_order_quickSearchAll=(.*)pageLocator:T\.evalJson\(unescape\(")(.*)(?="\)\))/g)()
    // 订单匹配结果
    const orderQueryJSONString = orderQueryResponseText.match(orderQueryTextReg)?.[0] || ''
    let orderQueryObj: any

    endTime = new Date().getTime()
    let log = `获取通途-订单信息结束: 邮箱 ${email}`
    try {
      orderQueryObj = JSON.parse(_unescape(orderQueryJSONString))
    } catch (e) {
      log += `; 订单信息解析失败`
      reject({ result: undefined, note: log })
    }
    if (orderQueryObj && !orderQueryObj.result) {
      log += `; 没有获取到订单信息`
      reject({ result: [], note: log })
    } else if (orderQueryObj?.result) {
      log += `; 获取订单信息成功`
    }
    log += `; 耗时 ${endTime - startTime}ms.\n`
    logger(event, { type: 'info', log })
    resolve(orderQueryObj?.result as any[] || [])
  })
}

/** 获取通途-订单状态|订单流程 */
const getTongToolOrderStatus = (event: Electron.IpcMainEvent, email: string, ORDERID: string):
  Promise<{ orderStatusText: string, orderRemarks: string[], orderFlowList: any[] }> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-订单状态|订单流程开始: 订单ID ${ORDERID}\n` })
  return new Promise(async (resolve, _) => {

    const orderStatusResponse = await fetch("https://shiming.tongtool.com/process/resume/order/sale/lookOrderPackage", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
        "Referer": `https://shiming.tongtool.com/search/order.htm?search_text_value=${encodeURIComponent(email)}&search_mark=all&source=global`,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `order.orderId=${ORDERID}&orderEdit.orderId=${ORDERID}&orderPackage.orderId=${ORDERID}&operateFlag=lookOrder&showTarge=&divFlag=${new Date().getTime()}25&operteHandler=searchOperteHandler&dataStoreFlag=editaftersep&isPlatformWarehouse=N&queryType=searchOpertOrder&requestId=&`,
      "method": "POST"
    })
    const orderStatusResponseText = await orderStatusResponse.text()
    const $ = cheerio.load(orderStatusResponseText)
    const orderStatusEle = $('input.hide')?.parent()?.parent() || null
    const orderRemarksEle = $('.fillet_blue_m') || []
    const orderFlowEle = $('div.pdtb5')?.find('p') || []
    let orderStatusText = ''
    let orderRemarks: string[] = []
    let orderFlowList: { time: string, status: string }[] = []
    if (orderStatusEle) {
      orderStatusText = (orderStatusEle.text() || '').replace(/\n|\t/g, '').trim()
    }
    if (orderRemarksEle.length > 0) {
      orderRemarksEle.each((_, item) => {
        const remark = $(item)?.text()?.replaceAll(/\n|\t/g, '').trim()
        orderRemarks.push(remark)
      })
    }
    if (orderFlowEle.length > 0) {
      orderFlowEle.each((_, item) => {
        const status = $(item).clone()?.children()?.remove()?.end()?.text()
        const time = $(item)?.find('span')?.text()
        orderFlowList.push({
          time,
          status
        })
      })
    }

    let log = `获取通途-订单状态|订单流程结束: 订单ID ${ORDERID}`
    log += !orderStatusText ? `; 没有获取到订单状态` : `; 获取订单状态成功`
    log += !orderFlowList.length ? `; 没有获取到订单流程` : `; 获取订单流程成功`
    endTime = new Date().getTime()
    log += `; 耗时 ${endTime - startTime}ms.\n`
    logger(event, { type: 'info', log })

    resolve({
      orderStatusText,
      orderRemarks,
      orderFlowList
    })
  })
}

/** 获取通途-货物信息 */
const getTongToolGoodsInfo = (event: Electron.IpcMainEvent, email: string, ORDERID: string): Promise<any[]> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-货物信息开始: 订单ID ${ORDERID}\n` })
  return new Promise(async (resolve, _) => {
    const goodsInfoResponse = await fetch("https://shiming.tongtool.com/process/resume/order/sale/获取订单商品信息", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
        "Referer": `https://shiming.tongtool.com/search/order.htm?search_text_value=${encodeURIComponent(email)}&search_mark=all&source=global`,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `order.orderId=${ORDERID}&orderEdit.orderId=${ORDERID}&operateFlag=lookOrder&isEpacket=&isEditGoods=0&divFlag=${new Date().getTime()}25&dataStoreFlag=0&operteHandler=searchOperteHandler&`,
      "method": "POST"
    })
    const goodsInfoResponseText = await goodsInfoResponse.text()
    const $ = cheerio.load(goodsInfoResponseText)
    const goodsInfoEle = $('.mb5.dot') || []
    const nameInfoEle = $('.bor_bom') || []
    let goodsInfoList: { name: string, skuList: string[], count: string }[] = []
    if (goodsInfoEle.length > 0) {
      goodsInfoEle.each((index, item) => {
        let skuList: string[] = []
        let count = $(item).find('.dbl.right')?.first()?.text().trim().replace(/\n|\t| /g, '') || ''
        let name = nameInfoEle[index] ? $(nameInfoEle[index]).find('.left.wrap>.left')?.first().next()?.text().trim().replace(/\n|\t| /g, '') : $(item).find('.pd5.mr5').children()?.text().trim().replace(/\n|\t| /g, '')
        const skuEleList = $(item).find('.dbl.w340.left').find('div>span')
        skuEleList.each((_, skuEle) => {
          skuList.push($(skuEle).text().trim().replace(/\n|\t| /g, ''))
        })
        goodsInfoList.push({
          name,
          skuList,
          count: count.split(':')?.[1] || count.split(':')?.[0],
        })
      })
    }
    let log = `获取通途-货物信息结束: 订单ID ${ORDERID}`
    log += !goodsInfoList.length ? `; 没有获取到订单货物信息` : `; 获取订单货物信息成功`
    endTime = new Date().getTime()
    log += `; 耗时 ${endTime - startTime}ms.\n`
    logger(event, { type: 'info', log })
    resolve(goodsInfoList)
  })
}

/** 获取通途-跟踪单号 */
const getTongToolTrackingNo = (event: Electron.IpcMainEvent, email: string, ORDERID: string): Promise<string> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-跟踪单号开始: 订单号 ${ORDERID}\n` })

  return new Promise(async (resolve, _) => {
    const trackingNoResponse = await fetch(`https://shiming.tongtool.com/process/resume/order/sale/获取订单仓库信息`, {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
        "Referer": `https://shiming.tongtool.com/search/order.htm?search_text_value=${encodeURIComponent(email)}&search_mark=all&source=global`,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `order.orderId=${ORDERID}&orderEdit.orderId=${ORDERID}&operateFlag=lookOrder&isEpacket=&divFlag=${new Date().getTime()}25&dataStoreFlag=0&operteHandler=searchOperteHandler&`,
      "method": "POST"
    })
    const trackingNoResponseText = await trackingNoResponse.text()
    const trackingNoTextReg = (() => /(?<=onclick="showTrackingNumberURL\(')(.*)(?='\);)/g)()
    const trackingNoText = trackingNoResponseText.match(trackingNoTextReg)?.[0] || ''

    let log = `获取通途-仓库信息结束: 订单号 ${ORDERID}`
    if (!trackingNoText) {
      log += `; 没有获取到跟踪单号`
    } else {
      log += `; 获取跟踪单号成功`
    }
    endTime = new Date().getTime()
    log += `; 耗时 ${endTime - startTime}ms.\n`
    logger(event, { type: 'info', log })

    resolve(trackingNoText)
  })
}


/** 获取通途-售后信息 */
const getTongToolSaleService = (event: Electron.IpcMainEvent, email: string, ORDERID: string): Promise<any[]> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-售后信息开始: 订单号 ${ORDERID}\n` })

  return new Promise(async (resolve, _) => {
    const saleServiceResponse = await fetch("https://shiming.tongtool.com/query/order/saleService", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
          "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
          "Referer": `https://shiming.tongtool.com/search/order.htm?search_text_value=${encodeURIComponent(email)}&search_mark=all&source=global`,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `q_c_orderId=${ORDERID}&q_c_dataStoreFlag=0&pageSize=20&showCondition=false&isPaginate=false&condition_prefix=q_c_&`,
      "method": "POST"
    })
    const saleServiceResponseText = await saleServiceResponse.text()
    const saleServiceTextReg = (() => /(?<=,pageLocator:T\.evalJson\(unescape\(")(.*)(?="\)\))/g)()
    const saleServiceJSONString = saleServiceResponseText.match(saleServiceTextReg)?.[1] || saleServiceResponseText.match(saleServiceTextReg)?.[1] || '{}'
    let saleServiceObj: any

    let log = `获取通途-售后信息结束: 订单号 ${ORDERID}`
    try {
      saleServiceObj = JSON.parse(_unescape(saleServiceJSONString))
    } catch (e) {
      saleServiceObj = { result: undefined }
      log += `; 售后信息解析失败`
    }
    if (!saleServiceObj?.result) {
      log += `; 没有获取到售后信息`
    } else {
      log += `; 获取售后信息成功`
    }
    endTime = new Date().getTime()
    log += `; 耗时 ${endTime - startTime}ms.\n`
    logger(event, { type: 'info', log })

    resolve(saleServiceObj?.result)
  })
}

/** 获取通途-付款信息 */
const getTongToolPayInfo = (event: Electron.IpcMainEvent, email: string, ORDERID: string): Promise<PayInfoType> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取通途-付款信息开始: 订单号 ${ORDERID}\n` })

  return new Promise(async (resolve, _) => {
    const payInfoResponse = await fetch("https://shiming.tongtool.com/process/resume/order/sale/获取订单付款信息", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not:A-Brand\";v=\"24\", \"Chromium\";v=\"134\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": `route_srv_id=${route_srv_id}; JSESSIONID=${JSESSIONID}`,
        "Referer": `https://shiming.tongtool.com/search/order.htm?search_text_value=${encodeURIComponent(email)}&search_mark=all&source=global`,
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `order.orderId=${ORDERID}&orderEdit.orderId=${ORDERID}&operateFlag=lookOrder&isEpacket=&divFlag=${new Date().getTime()}25&dataStoreFlag=0&operteHandler=searchOperteHandler&`,
      "method": "POST"
    })
    const payInfoResponseText = await payInfoResponse.text()
    const $ = cheerio.load(payInfoResponseText)
    const payTotalInfoEle = $('div.dot-ore') || ''
    const payHistoryInfoEles = $('div.dot>div.mt3:first-child') || []
    // let payInfo: PayInfoType = { totalInfo: '', historyInfo: [] }
    let totalInfo: PayInfoType['totalInfo'] = ''
    let historyInfo: PayInfoType['historyInfo'] = []
    let log = `获取通途-付款信息结束: 订单号 ${ORDERID}`
    if (payTotalInfoEle) {
      totalInfo = (payTotalInfoEle.text() || '').replace(/\n|\t|(  )/g, '')
      log += `; 获取付款信息成功`
    } else {
      log += '; 没有获取到付款信息'
    }
    if (payHistoryInfoEles.length > 0) {
      payHistoryInfoEles.each((_, item) => {
        const leftText = $(item).find('.left').find('span:last-child').text().replace(/\n|\t/g, ' ').replace('  ', '')
        const rightText = $(item).find('.right').find('span:last-child').text().replace(/\n|\t/g, ' ').replace('  ', '')
        historyInfo.push({ leftText, rightText })
      })
      log += `; 获取付款历史信息成功`
    } else {
      log += '; 没有获取到付款历史信息'
    }
    endTime = new Date().getTime()
    log += `; 耗时: ${endTime - startTime}ms\n`
    logger(event, { type: 'info', log })
    resolve({ totalInfo, historyInfo })
  })
}

/** 获取Traking物流信息 */
const getTrackingInfo = async (event: Electron.IpcMainEvent, trackingNoText: string): Promise<string> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `获取Track718-物流信息开始: 跟踪单号 ${trackingNoText}\n` })

  return new Promise(async (resolve, _) => {
    if (!trackingNoText) {
      logger(event, { type: 'error', log: `获取Track718-物流信息结束: 跟踪单号不存在\n` })
      resolve(`跟踪单号不存在`)
    }
    let { key: trackKey = '' } = trackApi.filter(item => item.regExp.test(trackingNoText))[0] || {}
    if (!trackKey) {
      logger(event, { type: 'error', log: `获取Track718-物流信息结束: 没有匹配跟踪单号为 ${trackingNoText} 的物流商\n` })
      resolve(`没有匹配跟踪单号为 ${trackingNoText} 的物流商`)
    }
    const requestBody = {
      "tracks": [
        {
          "track": `${trackingNoText}`,
          "key": `${trackKey}`
        }
      ],
      "uuid": "0.22410817892524082-1749831708000",
      "isChoose": false,
      "referrer": `"https://www.track718.us/zh-CN/detail?nums=${trackingNoText}`,
      "cache": true,
      "webDateTime": dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    const tracking718ApiSign = AESCryptoToMd5(JSON.stringify(requestBody))
    const packageLocationResponse = await fetch("https://apigetway.track718.net/track/real_query_multi", {
      "credentials": "include",
      "headers": {
        "Host": "apigetway.track718.net",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "application/json;charset=UTF-8",
        "X-Requested-With": "XMLHttpRequest",
        "Vsid": "ec748cb6bff3269b7e5dc29e2bff4a8f",
        "Track718-API-Sign": tracking718ApiSign,
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "Authorization": "",
        "Priority": "u=0",
        "Pragma": "no-cache",
        "Cache-Control": "no-cache"
      },
      "referrer": "https://www.track718.us/",
      "body": JSON.stringify(requestBody),
      "method": "POST",
      "mode": "cors"
    })
    let packageLocationJSON: any
    let log = `获取Track718-物流信息结束: 跟踪单号 ${trackingNoText}`
    try {
      packageLocationJSON = await packageLocationResponse.json()
    } catch (e) {
      log += `; 物流信息解析失败`
    }
    const packageLocation = packageLocationJSON?.data?.[0]?.latest || {}
    const packageStatusText = ((packageLocation?.ondate || '') + ' ' + (packageLocation?.status || '')).trim() || ''

    if (!packageStatusText) {
      log += '; 没有获取到物流信息'
    } else {
      log += '; 获取物流信息成功'
    }
    endTime = new Date().getTime()
    log += `; 耗时: ${endTime - startTime}ms\n`
    logger(event, { type: 'info', log })

    resolve(packageStatusText)
  })
}

/** 订单备注 */
const remarkOrder = async (event: Electron.IpcMainEvent, orderId: string, remark: string): Promise<string> => {
  let startTime = new Date().getTime(), endTime = 0
  logger(event, { type: 'info', log: `备注开始: 订单号 ${orderId}\n` })
  return new Promise(async (resolve, _) => {
    let remarkOrderResponse = await fetch("https://shiming.tongtool.com/process/resume/order/main/%E4%BF%9D%E5%AD%98%E8%AE%A2%E5%8D%95%E5%A4%87%E6%B3%A8", {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest",
        "cookie": "route_srv_id=831eebeee2ed995174c5866729e9b548; JSESSIONID=0405CA66CAC8B80460BE0904F1E14CFC",
        "Referer": "https://shiming.tongtool.com/search/order.htm?search_text_value=Patrick%2520Gustave&search_mark=all&source=global",
        "Referrer-Policy": "strict-origin-when-cross-origin"
      },
      "body": `orderId=${orderId}&orderRemark=${encodeURIComponent(remark)}&dataStoreFlag=0&isPlatformWarehouse=N&`,
      "method": "POST"
    })
    let remarkOrderResponseText = await remarkOrderResponse.text()
    endTime = new Date().getTime()
    let log = `备注结束: 订单号 ${orderId}; 耗时: ${endTime - startTime}ms\n`
    logger(event, { type: 'info', log })
    resolve(remarkOrderResponseText)
  })
}

/** 退款 */
const refundOrder = async (event: Electron.IpcMainEvent, orderId: string, money: string): Promise<string> => {
  console.log(event, orderId, money)
  return new Promise(async (resolve, _) => {
    resolve('ok')
  })
}

// 创建通途工具窗口
const createTongToolWindow = (): void => {

  const tongtoolSession = session.fromPartition('persist:tongtool', { cache: true })

  const setTongtoolCookies = () => {
    const tongtoolCookies = electronStore.get('tongtoolCookies') as any[]
    if (tongtoolCookies) {
      tongtoolCookies.forEach((cookie: any) => {
        const url = 'https://' + (cookie.domain[0] === '.' ? cookie.domain.slice(1) : cookie.domain)
        const name = cookie.name
        const value = cookie.value
        let _cookie = {
          url,
          name,
          value,
          path: cookie.path,
          secure: cookie.secure,
          httpOnly: cookie.httpOnly,
          sameSite: cookie.sameSite,
          domain: cookie.domain,
          expirationDate: dayjs('2026-01-01').toDate().getTime(),
        }
        tongtoolSession.cookies.set(_cookie)
      })
    }
  }

  setTongtoolCookies()

  const tongtoolWindow = new BrowserWindow({
    width: 1500,
    height: 1000,
    show: true,
    x: 200,
    y: 100,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      session: tongtoolSession,
      partition: 'persist:tongtool',
      // 禁用自动填充（核心配置）
      enableBlinkFeatures: 'AutofillDisabler',
      contextIsolation: true,
      nodeIntegration: true,
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      // webSecurity: false,
    }
  })

  tongtoolWindow.webContents.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:137.0) Gecko/20100101 Firefox/137.0'

  tongtoolWindow.loadURL('https://shiming.tongtool.com/search/order.htm')

  tongtoolWindow.webContents.setWindowOpenHandler(({ url }: { url: string }) => {
    url = url
    return {
      action: 'allow',
      overrideBrowserWindowOptions: {
        webPreferences: {
          session: tongtoolSession,
          partition: 'persist:tongtool',
        }
      }
    }
  })

  replaceLoadHeader()

  // 获取当前窗口的cookie
  ipcMain.on('r2m-set-tongtool-cookie', async (_) => {
    const newCookies = await tongtoolSession.cookies.get({})
    // console.log(newCookies)
    electronStore.set('tongtoolCookies', newCookies)
    route_srv_id = newCookies.filter((cookie) => cookie.name === 'route_srv_id')?.[0]?.value || '831eebeee2ed995174c5866729e9b548'
    JSESSIONID = newCookies.filter((cookie) => cookie.name === 'JSESSIONID')?.[0]?.value || 'A4E410FADC004CA0AAADECD0C2EEAA5E'
    setTongtoolCookies()
  })

  /** 批量获取通途订单内容 */
  ipcMain.on('r2m-query-all-order', async (event, emailList: string[], threads = 2) => {
    let group = Array(Math.ceil(emailList.length / threads)).fill(null).map((_, i) => emailList.slice(i * threads, (i + 1) * threads))
    let allTongtoolOrderList: any[] = Array(emailList.length).fill(undefined)
    for (let groupIndex = 0; groupIndex < group.length; groupIndex++) {
      let promises = Array(threads + 1).fill(undefined)
      for (let threadIndex = 0; threadIndex < threads; threadIndex++) {
        const email = group[groupIndex][threadIndex]
        if (!email) continue
        promises[threadIndex] = Promise.try(getTongToolOrderInfo, event, email).then((result) => {
          return result
        }).then(async (tongtoolOrderList: any[]) => {
          // let promises: Array<[Promise<any>, string]> = []
          for (let i = 0; i < tongtoolOrderList.length; i++) {
            let singleOrderWithNamePromise: Array<[Promise<any>, string]> = [
              [getTongToolOrderStatus(event, email, tongtoolOrderList[i].ORDERID), 'orderStatus'], // 订单状态
              [getTongToolGoodsInfo(event, email, tongtoolOrderList[i].ORDERID), 'goodsInfo'], // 货品信息
              [getTongToolTrackingNo(event, email, tongtoolOrderList[i].ORDERID), 'trackingNo'], // 仓库信息
              [getTongToolSaleService(event, email, tongtoolOrderList[i].ORDERID), 'saleService'], // 售后信息
              [getTongToolPayInfo(event, email, tongtoolOrderList[i].ORDERID), 'payInfo'], // 付款信息
            ]
            const withNamePromisesResult: any = await new Promise((resolve, _) => {
              let promisesResult: any = {
                orderStatus: undefined,
                goodsInfo: undefined,
                trackingNo: undefined,
                saleService: undefined,
                payInfo: undefined,
                trackingInfo: undefined
              }
              // 返回的结果数量
              let promisesResultCount = 0
              singleOrderWithNamePromise.forEach((promiseWithName) => {
                promiseWithName[0].then((result) => {
                  promisesResult[promiseWithName[1]] = result
                }).finally(async () => {
                  promisesResultCount++
                  // 如果当前 promise 是获取跟踪单号，则同步获取物流信息
                  if (promiseWithName[1] === 'trackingNo') {
                    let trackingNo = promisesResult['trackingNo'] || ''
                    promisesResult.trackingInfo = await getTrackingInfo(event, trackingNo)
                  }
                  if (promisesResultCount === singleOrderWithNamePromise.length) {
                    resolve(promisesResult)
                  }
                })
              })
            })
            tongtoolOrderList[i] = {
              ...tongtoolOrderList[i],
              ...withNamePromisesResult
            }
          }
          allTongtoolOrderList[groupIndex * threads + threadIndex] = tongtoolOrderList
        }).catch(({ result }) => {
          allTongtoolOrderList[groupIndex * threads + threadIndex] = result
        })
      }
      // promise 延时返回 随机等待 5-10 秒
      promises[threads] = new Promise((resolve) => {
        let delay = Number(Math.random().toFixed(3)) * 5000 + 5000
        event.reply('message', 'info', `延时等待${delay}ms`, delay)
        setTimeout(() => {
          resolve('timeSleep')
        }, delay)
      })
      await Promise.allSettled(promises)
    }
    event.reply('m2r-query-all-order', allTongtoolOrderList, '查询完成')
  })

  /** 获取单个通途订单内容 */
  ipcMain.on('r2m-query-single-order', (event, email: string, dataIndex: number) => {

    console.info('调试信息: email: ', email)

    Promise.try(getTongToolOrderInfo, event, email).then((result) => {
      return result
    }).then(async (tongtoolOrderList) => {
      // let promises: Array<[Promise<any>, string]> = []
      for (let i = 0; i < tongtoolOrderList.length; i++) {
        let singleOrderWithNamePromise: Array<[Promise<any>, string]> = [
          [getTongToolOrderStatus(event, email, tongtoolOrderList[i].ORDERID), 'orderStatus'], // 订单状态
          [getTongToolGoodsInfo(event, email, tongtoolOrderList[i].ORDERID), 'goodsInfo'], // 货品信息
          [getTongToolTrackingNo(event, email, tongtoolOrderList[i].ORDERID), 'trackingNo'], // 仓库信息
          [getTongToolSaleService(event, email, tongtoolOrderList[i].ORDERID), 'saleService'], // 售后信息
          [getTongToolPayInfo(event, email, tongtoolOrderList[i].ORDERID), 'payInfo'], // 付款信息
        ]
        const withNamePromisesResult: any = await new Promise((resolve, _) => {
          let promisesResult: any = {
            orderStatus: undefined,
            goodsInfo: undefined,
            trackingNo: undefined,
            saleService: undefined,
            payInfo: undefined,
            trackingInfo: undefined
          }
          // 返回的结果数量
          let promisesResultCount = 0
          singleOrderWithNamePromise.forEach((promiseWithName) => {
            promiseWithName[0].then((result) => {
              promisesResult[promiseWithName[1]] = result
            }).finally(async () => {
              promisesResultCount++
              // 如果当前 promise 是获取跟踪单号，则同步获取物流信息
              if (promiseWithName[1] === 'trackingNo') {
                let trackingNo = promisesResult['trackingNo'] || ''
                promisesResult.trackingInfo = await getTrackingInfo(event, trackingNo)
              }
              if (promisesResultCount === singleOrderWithNamePromise.length) {
                resolve(promisesResult)
              }
            })
          })
        })
        tongtoolOrderList[i] = {
          ...tongtoolOrderList[i],
          ...withNamePromisesResult
        }
      }
      event.reply('m2r-query-single-order', tongtoolOrderList, dataIndex, '查询完成')
    }).catch(({ result, note}) => {
      event.reply('m2r-query-single-order', result, dataIndex, note)
    })
  })

  /** 备注订单 */
  ipcMain.on('r2m-remark', async (event, remark, item, index) => {
    console.info('调试信息: ', remark)
    item.remark ??= ''
    item.remark = remark
    // await remarkOrder(event, item.ORDERID, remark)
    console.log(remarkOrder)
    event.reply('m2r-remark', item, index, { type: 'success', note: '备注成功' })
  })

  /** 退款 */
  ipcMain.on('r2m-refund', async (event, refundAmount, item, index) => {
    console.info('调试信息: ', refundAmount)
    item.refundList ??= []
    item.refundList.push(refundAmount)
    // await refundOrder(event, item.ORDERID, refundAmount)
    console.log(refundOrder)
    event.reply('m2r-refund', item, refundAmount, index, { type: 'success', note: '退款成功' })
  })

  // 页面加载完成后
  tongtoolWindow.webContents.on('did-finish-load', async () => {
    // const document = await tongtoolWindow.webContents.executeJavaScript('document')
    // console.log(document.title)
  })

  tongtoolWindow.on('close', () => {
    tongtoolSession.cookies.flushStore()
  })
}

export default createTongToolWindow
